package com.oscar.ehome.view.pageview;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.oscar.ehome.R;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.pagebean.HdBean;
import com.oscar.ehome.bean.pagebean.SignNameBean;
import com.oscar.ehome.presenter.PagePresenter;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshBase;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshListView;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.view.MyList;
import com.oscar.ehome.utils.view.progressview.ProgressFrameLayout;
import com.oscar.ehome.utils.xrefresh.XRefreshView;
import com.oscar.ehome.view.loginview.CaptureActivity;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.messageview.MessageDetilActivity;
import com.oscar.ehome.view.pageview.adapter.HdAdapter;
import com.oscar.ehome.view.pageview.view.HdView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by oscar
 * author: MengWanhe
 * date: On 2017/7/7
 * 活动页
 */
public class HuoDongActivity extends BasesActivity<HdView, PagePresenter> implements HdView,XRefreshView.XRefreshViewListener, AdapterView.OnItemClickListener,
        HdAdapter.IntentListener, EasyPermissions.PermissionCallbacks, TextWatcher, ProgressFrameLayout.AgainRequestListener {

    /**
     * 返回
     */
    @BindView(R.id.huodongtitle_img_back)
    ImageView huodongtitleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.huodongtitle_layout_left)
    RelativeLayout huodongtitleLayoutLeft;
    /**
     * 搜索的活动
     */
    @BindView(R.id.serach_huodong_edtext)
    EditText serachHuodongEdtext;
    /**
     * 搜索
     */
    @BindView(R.id.huodongmessage_serach_img)
    ImageView huodongmessageSerachImg;
    /**
     * 列表
     */
    @BindView(R.id.huodong_listview)
    MyList messageListview;
    /**
     * 活动搜索
     */
    @BindView(R.id.hdserach_buton)
    Button hdserachButon;
    /**
     *
     */
    @BindView(R.id.title_image_right)
    ImageView titleImageRight;

    @BindView(R.id.hd_fragment)
    ProgressFrameLayout hdFragment;
    /**
     * title布局
     */
    @BindView(R.id.hd_title)
    RelativeLayout hd_title;


    @BindView(R.id.message_refview)
    XRefreshView messageRefview;
    PagePresenter hdpersenter;//用来网络请求
    HdAdapter adapter;
    public static long lastRefreshTime;
    private List<HdBean.ListBean> list = new ArrayList<>();//数据

    String token = "";
    private int page = 1;//页数
    private int page_size = 20;//每页的条数
    int size = 0;
    int camera = 0;//是否有权限开摄像头
    private String eventId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_huodong);
        ButterKnife.bind(this);
        hd_title.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(HuoDongActivity.this).getSystemConfig().getColor()));
        onClick();
        initView();
        initData();
        getMessage();
    }

    @Override
    protected PagePresenter createPresenter() {
        hdpersenter = new PagePresenter(this);
        return hdpersenter;
    }

    /**
     * 判断是否有网
     */
    public boolean isNetWork() {
        boolean netWork = true;
        if (!CommonUtils.isNetConn(HuoDongActivity.this)) {
            netWork = false;
            return netWork;
        }
        return netWork;
    }

    /**
     * 初始化
     */
    public void initView() {
        huodongtitleImgBack.setImageResource(R.mipmap.fanhui);
        token = SystemConfigFactory.getInstance(HuoDongActivity.this).getSystemConfig().getToken();
        serachHuodongEdtext.setHintTextColor(getResources().getColor(R.color.gray_99));
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        adapter = new HdAdapter(HuoDongActivity.this, list);
        messageListview.setAdapter(adapter);
        adapter.setOnINtentClickListener(this);
//        huodongListview.doPullRefreshing(true, 500);
    }

    /**
     * 加载数据
     */
    public void initData() {
        if (isNetWork()) {
            hdFragment.stopRefresh();
            messageListview.setVisibility(View.VISIBLE);
            String s = String.valueOf(page);
            hdpersenter.hdlist(token, s, "20", "");
            showLoading();
        } else {
            messageListview.setVisibility(View.GONE);
            hdFragment.setVisibility(View.VISIBLE);
            hdFragment.setLoadFail();
        }
    }

    /**
     * 点击
     */
    public void onClick() {

        messageListview.setOnItemClickListener(this);
        serachHuodongEdtext.addTextChangedListener(this);
        hdFragment.setAgainRequestListener(this);
        messageRefview.setXRefreshViewListener(this);
        // 设置是否可以下拉刷新
        messageRefview.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        messageRefview.setPullLoadEnable(false);
        // 设置上次刷新的时间
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        //当下拉刷新被禁用时，调用这个方法并传入false可以不让头部被下拉
        messageRefview.setMoveHeadWhenDisablePullRefresh(true);
        // 设置时候可以自动刷新
        messageRefview.setAutoRefresh(false);
    }

    /**
     * 设置键盘的搜索事件
     */
    public void getMessage() {
        serachHuodongEdtext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(HuoDongActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    checkMessage();
                }
                return false;
            }
        });

    }

    /**
     * 点击
     */
    @OnClick({R.id.huodongtitle_img_back, R.id.hdserach_buton, R.id.title_image_right
    })
    public void OnClicked(View view) {
        switch (view.getId()) {
            case R.id.huodongtitle_img_back://返回
                finish();
                break;
            case R.id.hdserach_buton://搜索
                checkMessage();
                break;
        }
    }

    //搜索信息
    private void checkMessage() {

        String s = String.valueOf(page);
        hdpersenter.hdlist(token, s, "20", serachHuodongEdtext.getText().toString().trim());
        showLoading();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String type = "";
        if (list.get(position).getEventDetailType() != null) {
            type = list.get(position).getEventDetailType();
        }
        if ("1".equals(type) || "".equals(type)) {
            Intent intent = new Intent(this, BannerWebActivity.class);
            intent.putExtra("contentsrc", list.get(position).getEventSrc());
            intent.putExtra("name", list.get(position).getTtitle());
            intent.putExtra("type", "hd");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, HtmlActivity.class);
            intent.putExtra("eventHtml", list.get(position).getEventHtml());
            intent.putExtra("name", list.get(position).getTtitle());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }




    @Override
    public void getHdList(HdBean result) {
        dismissLoading();

        if (result != null) {
            if (page == 1) {
                list.clear(); // 将原有的内容清空
            }
            list = result.getList();
            size = list.size();
            if (size > 0) {
                messageRefview.stopRefresh();
                messageListview.setVisibility(View.VISIBLE);
                hdFragment.stopRefresh();
                if (size < page_size && list.size() > 0) {
                    messageRefview.stopLoadMore();
                }
                adapter.setLists(list);
            } else {
                messageListview.setVisibility(View.GONE);
                hdFragment.setVisibility(View.VISIBLE);
                hdFragment.setNoResult();
            }
        } else {
            messageListview.setVisibility(View.GONE);
            hdFragment.setNoResult();
        }
    }

    //活动签到未用到
    @Override
    public void saveEventSign(SignNameBean baseBean) {

    }

    @Override
    public void erroy() {
        dismissLoading();
        messageRefview.stopRefresh();
        ToastUtil.show(HuoDongActivity.this, getString(R.string.erry));
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        messageRefview.stopRefresh();
        ToastUtil.show(HuoDongActivity.this, result);
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(HuoDongActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(HuoDongActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onIntentClick(int postion) {
        isPressmion(postion);
    }

    /**
     * 查看是否是6。0以上系统
     */
    public void isPressmion(int postion) {
        eventId = list.get(postion).getId();

        if (Build.VERSION.SDK_INT >= 23) {
            camera = 1;
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
            if (EasyPermissions.hasPermissions(this, perms)) {//检查是否获取该权限
                Intent intent = new Intent(HuoDongActivity.this, CaptureActivity.class);//进入扫二维码页面
                intent.putExtra("isIdcard", 2);
                intent.putExtra("eventId", eventId);
                startActivity(intent);
            } else {
                //第二个参数是被拒绝后再次申请该权限的解释
                //第三个参数是请求码
                //第四个参数是要申请的权限
                EasyPermissions.requestPermissions(this, "签到将要开启拍照权限！", 0, perms);
            }
        } else {
            Intent intent = new Intent(HuoDongActivity.this, CaptureActivity.class);//进入扫二维码页面
            intent.putExtra("isIdcard", 2);
            intent.putExtra("eventId", eventId);
            startActivity(intent);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (camera == 1) {
            Intent intent = new Intent(HuoDongActivity.this, CaptureActivity.class);
            intent.putExtra("isIdcard", 2);
            intent.putExtra("eventId", eventId);
            startActivity(intent);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, "为了您能使用相机功能，请开启相机权限！")
                    .setTitle("提示")
                    .setPositiveButton("去设置")
                    .setNegativeButton("取消", null)
                    .setRequestCode(0)
                    .build()
                    .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > 0) {
            huodongmessageSerachImg.setVisibility(View.GONE);
        } else if (s.length() == 0) {
            huodongmessageSerachImg.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void againRequest() {
        if (isNetWork()) {
            initData();
        } else {
            ToastUtil.show(HuoDongActivity.this, R.string.pull_to_refresh_network_error);
        }
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onRefresh(boolean isPullDown) {
        lastRefreshTime = messageRefview.getLastRefreshTime();
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        page = 1;
        String s = String.valueOf(page);

        if ("".equals(serachHuodongEdtext.getText().toString().trim())) {
            hdpersenter.hdlist(token, s, "20", "");
        } else {
            hdpersenter.hdlist(token, s, "20", serachHuodongEdtext.getText().toString().trim());
        }

        showLoading();
    }

    @Override
    public void onLoadMore(boolean isSilence) {
        page++;
        String s = String.valueOf(page);

        if ("".equals(serachHuodongEdtext.getText().toString().trim())) {
            hdpersenter.hdlist(token, s, "20", "");
        } else {
            hdpersenter.hdlist(token, s, "20", serachHuodongEdtext.getText().toString().trim());
        }
        showLoading();
    }

    @Override
    public void onRelease(float direction) {

    }

    @Override
    public void onHeaderMove(double headerMovePercent, int offsetY) {

    }
}
